// @login & register 
const express = require("express")
const router = express.Router()
const bcrypt = require('bcrypt')
const gravatar = require('gravatar')
const jwt = require('jsonwebtoken')
const keys = require('../../config/db')
const User = require('../../models/User')
const password = require('passport')

router.get("/hello", (req,res) => {
    res.json({msg:"login success"})
})
// $rout POST api/usrs/register
// @desc user register new account
// @access public
router.post('/register',function(req,res){
    
    User.findOne({email:req.body.email})
        .then((user) => {
            if ( user ) {
                return res.status(400).json({email:"邮箱已被注册！"})
            } else {
                const vat = gravatar.url(req.body.email,{s:200,r:"pg",d:'mm'})
                const newUser = new User({
                    name : req.body.name,
                    email:req.body.email,
                    avatar : vat,
                    password : req.body.password
                })

                bcrypt.genSalt(10,function(err,salt) {
                    bcrypt.hash(newUser.password,salt,(err,hash)=> {
                        if ( err ) throw err
                        newUser.password = hash
                        newUser.save().then(user => res.json(user))
                    })
                })
            }
        })
   
})

// $rout POST api/usrs/login
// @desc user login new account
// @access public
router.post('/login',function(req,res){
    const email = req.body.email
    const pwd = req.body.password
    User.findOne({email:req.body.email})
        .then((user) => {
            if ( !user ) {
                return res.status(400).json({email:"用户不存在！"})
            } 
            
            bcrypt.compare(pwd,user.password)
                  .then((isMatch) => {
                      if ( isMatch ) {
                          const rule = {id:user.id,name: user.name}
                          jwt.sign(rule,keys.tokenKey,{expiresIn:1800},(err,token) => {
                              if (err) throw err
                              res.json({
                                  success:true,
                                  token : "Bearer "+token
                              })
                          })
                          //res.json({msg:"login success"})
                      } else {
                          return res.status(400).json({password:"用户密码错误"})
                      }
                  })
            
            
        })
   
})

// $rout GET api/usrs/token
// @desc user login new account
// @access pivate
router.get('/token',password.authenticate('jwt',{session:false}),(req,res) => {
    res.json(req.user)
})
module.exports = router 